package com.ruoyi.site.controller;

import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.site.service.IUserLicensesService;
import org.apache.commons.io.IOUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.site.domain.Sfx;
import com.ruoyi.site.service.ISfxService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import static com.ruoyi.common.utils.ServletUtils.getRequest;

/**
 * 音效Controller
 * * @author chuckeytang
 * @date 2025-08-17
 */
@RestController
@RequestMapping("/site/sfx")
public class SfxController extends BaseController
{
    @Autowired
    private ISfxService sfxService;

    @Autowired(required = false)
    private TokenService tokenService;

    @Autowired
    private IUserLicensesService userLicensesService;

    /**
     * 查询音效列表
     */
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody Sfx sfx)
    {
        startPage();
        List<Sfx> list = sfxService.selectSfxList(sfx);
        return getDataTable(list);
    }

    /**
     * 导出音效列表
     */
    @Log(title = "音效", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Sfx sfx)
    {
        List<Sfx> list = sfxService.selectSfxList(sfx);
        ExcelUtil<Sfx> util = new ExcelUtil<Sfx>(Sfx.class);
        util.exportExcel(response, list, "音效数据");
    }

    /**
     * 获取音效详细信息
     */
    @GetMapping(value = "/{sfxId}")
    public AjaxResult getInfo(@PathVariable("sfxId") Long sfxId)
    {
        return success(sfxService.selectSfxBySfxId(sfxId));
    }

    /**
     * 新增音效
     */
    @PreAuthorize("@ss.hasPermi('site:sfx:add')")
    @Log(title = "音效", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Sfx sfx)
    {
        return toAjax(sfxService.insertSfx(sfx));
    }

    /**
     * 修改音效
     */
    @PreAuthorize("@ss.hasPermi('site:sfx:edit')")
    @Log(title = "音效", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Sfx sfx)
    {
        return toAjax(sfxService.updateSfx(sfx));
    }

    /**
     * 删除音效
     */
    @PreAuthorize("@ss.hasPermi('site:sfx:remove')")
    @Log(title = "音效", businessType = BusinessType.DELETE)
    @DeleteMapping("/{sfxIds}")
    public AjaxResult remove(@PathVariable Long[] sfxIds)
    {
        return toAjax(sfxService.deleteSfxBySfxIds(sfxIds));
    }

    @GetMapping("/sfx/download/{sfxId}") // 假设您在 SfxController 中
    public void downloadSfxFile(@PathVariable("sfxId") Long sfxId, HttpServletResponse response) {

        // 1. 获取用户ID
        Long currentUserId = null;
        try {
            LoginUser loginUser = tokenService.getLoginUser(getRequest());
            currentUserId = loginUser.getUserId();
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401
            return;
        }

        // 2. 检查购买状态
        boolean hasLicense = userLicensesService.checkUserHasLicense(currentUserId, sfxId, "sfx"); // <--- 使用授权服务

        if (!hasLicense) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 403
            return;
        }

        // 3. 获取文件信息
        Sfx sfx = sfxService.selectSfxBySfxId(sfxId);
        if (sfx == null || StringUtils.isEmpty(sfx.getAudioFileUrl())) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 4. 执行下载
        try (InputStream inputStream = new URL(sfx.getAudioFileUrl()).openStream()) {

            // 5. 【新增】记录下载次数 (同样需要实现查找 licenseId 的逻辑)
            // userLicensesService.recordDownloadByProduct(currentUserId, sfxId, "sfx");

            // 6. 设置响应头
            response.setContentType("audio/mpeg");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sfx.getTitle() + ".mp3", "UTF-8"));

            // 7. 复制流
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();

        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        }
    }

    /**
     * 获取筛选器选项
     */
    @GetMapping("/filter-options")
    public AjaxResult getFilterOptions() {
        return success(sfxService.getFilterOptions());
    }
}